package com.mf.ui.widgets;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

public class GradientBackgroundView extends View {
    private Paint paint;
    private int startColor = Color.parseColor("#89f7fe");
    private int endColor = Color.parseColor("#66a6ff");
    private int currentStartColor = startColor;
    private int currentEndColor = endColor;

    public GradientBackgroundView(Context context) {
        super(context);
        init();
    }

    public GradientBackgroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint();
        startAnimation();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        LinearGradient gradient = new LinearGradient(0, 0, width, height, currentStartColor, currentEndColor, Shader.TileMode.CLAMP);
        paint.setShader(gradient);
        canvas.drawRect(0, 0, width, height, paint);
    }

    private void startAnimation() {
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
        animator.setDuration(3000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float fraction = animation.getAnimatedFraction();
                currentStartColor = blendColors(startColor, endColor, fraction);
                currentEndColor = blendColors(endColor, startColor, fraction);
                invalidate();
            }
        });
        animator.start();
    }

    private int blendColors(int color1, int color2, float ratio) {
        float inverseRatio = 1 - ratio;
        float r = Color.red(color1) * ratio + Color.red(color2) * inverseRatio;
        float g = Color.green(color1) * ratio + Color.green(color2) * inverseRatio;
        float b = Color.blue(color1) * ratio + Color.blue(color2) * inverseRatio;
        return Color.rgb((int) r, (int) g, (int) b);
    }
}
